import codecs
import collections
import os
import traceback

import numpy as np
import pandas
import pandas as pd
from loguru import logger

from models.global_config import glm
from models.stock_model import StockNumber, DayInfo
from mylib import gen_excel
from mylib.myfile import insert_line


def get_all_stock(trade_date, stocks):
    df = pd.read_csv('all.csv')
    for row in df.index:
        if stocks is not None and df.loc[row]['ts_code'] not in stocks:
            continue
        sn = StockNumber(df.loc[row])
        sn.list_date = df.loc[row]['list_date']
        if '退' in sn.name:
            continue
        if 'ST' in sn.name:
            continue
        if not str(sn.ts_code).startswith('60') \
                and not str(sn.ts_code).startswith('00'):
            continue
        return analysis_stock(trade_date, sn)


def analysis_stock(trade_date, sn):
    csv_path = f'stocks/{sn.ts_code}.csv'
    df2 = pd.read_csv(csv_path)
    # 计算连续上涨和连续下跌5次
    down_arr = []
    for row2 in df2.index:
        di = DayInfo(sn, df2.loc[row2])
        if int(di.trade_date) > int(trade_date):
            continue
        if di.pct_chg > 0:
            link_code_arr = sn.ts_code.split('.')
            link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
            hyperlink = f'"https://xueqiu.com/S/{link_code}"'
            date_arr_hyp = f'=HYPERLINK({hyperlink}),{di.name}'
            # msg = f'{date_arr_hyp},{trade_date},{len(down_arr)}\n'
            msg = f'{len(down_arr)},{date_arr_hyp}'
            return trade_date, msg
        else:
            down_arr.append(di)
        # if len(up_time_arr) > 5 and len(down_time_arr) > 5:
        #     link_code_arr = sn.ts_code.split('.')
        #     link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
        #     hyperlink = f'"https://xueqiu.com/S/{link_code}"'
        #     date_arr_hyp = f'= HYPERLINK({hyperlink},{di.name})'
        #     aa = codecs.open('aa.csv', 'a+', encoding='utf-8')
        #     avg_up = round(np.average(up_time_arr), 2)
        #     avg_down = round(np.average(down_time_arr), 2)
        #     up_time_arr_str = '_'.join([str(item) for item in up_time_arr])
        #     down_time_arr_str = '_'.join([str(item) for item in down_time_arr])
        #     msg = f'{di.trade_date}, {date_arr_hyp}, {row2}, {up_time_arr_str}, {avg_up}, {down_time_arr_str}, {avg_down}'
        #     logger.info(msg)
        #     aa.write(msg)
        #     aa.write('\n')
        #     logger.info(f'计算完成{di.name} {di.trade_date}')
        #     logger.info(f'计算完成{di.name} {date_arr_hyp}')
        #     logger.info(f'计算完成{di.name} {row2}')
        #     logger.info(f'计算完成{di.name} {up_time_arr}')
        #     logger.info(f'计算完成{di.name} {avg_up}')
        #     logger.info(f'计算完成{di.name} {down_time_arr}')
        #     logger.info(f'计算完成{di.name} {avg_down}')
        #     return


def run(log_dir, start_date, end_date, stocks=None, bkd=0):
    trade_date_dict = collections.defaultdict()
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    logger.info(f'{log_dir} start')
    for idx, trade_date in enumerate(glm.get_all_trade_days(stocks[0])):
        if trade_date >= start_date:
            continue
        if end_date is not None and trade_date <= end_date:
            break
        if idx >= bkd:
            break
        logger.info(f'cal {trade_date}')
        try:
            trade_date, msg = get_all_stock(trade_date, stocks)
            trade_date_dict[trade_date] = msg
        except Exception as e:
            logger.error(traceback.format_exc())
            logger.error(e)
    return trade_date_dict
